EASY
Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once.
給定一個函數 fn作為參數,返回一個與原始函數相同的新函數,只不過它確保 fn 最多被調用一次。
太好了!昨天學到的剩餘參數今天也用上了!
const once = (fn)=>{
let wasCalled = false;
return (...args)=>{
if(!wasCalled){
wasCalled=true;
// 返回與原始函數相同的結果
// 做法:宣告新函式引用原始函式,同時將原始函數的參數傳遞給新函數
let result = fn(...args);
return result;
}else{
return undefined;
}
}
}
fn = (a,b,c) => (a + b + c);
const wrappedFn1 = once(fn);
console.log(wrappedFn1(1,2,3),wrappedFn1(4,5,6));
// 6 undefined
fn = (a,b,c) => (a * b * c);
const wrappedFn2 = once(fn);
console.log(wrappedFn2(5,7,4),wrappedFn2(2,3,6),wrappedFn2(4,6,8));
// 140 undefined undefined